'use strict';
/**
 * generate pages (route)
 */
var util = require('util');
var path = require('path');
var fs = require('fs');
var ScriptBase = require('../../lib/script-base');
var nbPreference = require('../../lib/nb-preference');
var _ = require('underscore');
_.mixin(require('underscore.inflections'));
/**
 * Constructor
 */
var Generator = module.exports = function()
{
	ScriptBase.apply(this , arguments);

};
// extend it
util.inherits(Generator , ScriptBase);
/**
 * scan the user components folder and see if there is other components to add to the page
 */
Generator.prototype.scanComponents = function()
{
	this.customComponents = [];
	var self = this;
	var localPath = path.join(process.cwd() , this.env.options.appPath , 'scripts' , 'components');

	fs.readdir(localPath , function(err , files)
	{
		self.customComponents = _.map(files , function(file)
		{
			var f = file.replace(self.scriptSuffix , '');
			return {name: _.classify(f) , value: file};
		});
	});
};

/**
 * Ask the user if they want to add other components
 */
Generator.prototype.askIfAddOtherComponents = function()
{
	if (!this.options['skip-check'] && this.customComponents.length>0) {
		var cb = this.async();
		this.prompt({
			type: 'confirm',
			name: 'add',
			message: (this.lang==='en') ? 'Would you like to add your components to page?' : '你想把你的组件(componet)加到页(page)吗？',
			default: true
		} , function(props)
		{
			this.add = props.add;
			cb();
		}.bind(this));
	}
	else {
		this.add = false;
	}
};

/**
 * actual implementation
 */
Generator.prototype.askForWhichOne = function()
{
	if (this.add) {
		var cb = this.async();
		var self = this;
		this.prompt({
			type: 'checkbox',
			choices: self.customComponents,
			message: (self.lang==='en') ? 'Pick the component you want to add to your page.' : '请选你想加入的组件(component).',
			name: 'component'
		}, function(props)
		{
			self.selectedComponents = _.map(props.component , function(comp)
			{
			 	return _.find(self.customComponents , {value: comp});
			});
			cb();
		}.bind(this));
	}
};

/**
 * actual implementation
 */
Generator.prototype.createPageFile = function()
{
	this.pageName = this.classedName;
	this.pageComponents = {};
	var self = this;
	_.each(this.selectedComponents , function(comp)
	{
		self.pageComponents[comp.name] = path.join('..' , 'components' , comp.value);
	});

	this.underscore = _;
	// a page is just a components, but we put it in the foler pages because we scan the components folder for standalone components
	// the only different is - its a combination of other components together
	this.appTemplate('page', path.join('scripts' , 'pages' , this.name));

};
